package com.song.service.Impl;

import com.song.dao.OrdersMapper;
import com.song.dao.ItemsMapper;
import com.song.pojo.Orders;
import com.song.pojo.Items;
import com.song.service.OrdersService;
import com.song.utils.UUIDUtils;
import com.song.vo.OrdersVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2020/12/29 - the current system date.
 * 10:21 - the current system time.
 */
@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private ItemsMapper itemsMapper;
    /**
     * 添加订单
     *
     * @param orders
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public int addOrders(Orders orders) {
        orders.setStatus(1);//1-待确认
        orders.setOrdersNo(UUIDUtils.randomUUID());
        //orders.setReserveDate(new Date());//预订时间为当前系统时间
        int count = ordersMapper.addOrders(orders);
        //判断订单是否添加成功，添加成功操作商品
        if(count>0){
            //查询商品信息
            Items items = itemsMapper.findBygetGoodsId(orders.getGoodsId());
            //库存-预订的数量
            items.setLiveNum(items.getLiveNum()-orders.getCounts());
            //已预订量+预订的数量
            items.setReservedNum(items.getReservedNum()+orders.getCounts());
            if (items.getLiveNum()==0) {
                //修改商品状态为已预订完(编号1)
                items.setStatus(1);
            }
            //调用修改商品信息的方法
            itemsMapper.updateItems(items);
        }
        return count;
    }

    public List<Orders> findOrdersList(OrdersVo ordersVo) {
        return ordersMapper.findOrdersList(ordersVo);
    }

    public int updateOrders(Orders orders) {

        return ordersMapper.updateOrders(orders);
    }

    @Override
    public List<Orders> findByUserId(Long id) {
        return ordersMapper.findByUserId(id);
    }
}

